package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private WorkspaceService workspaceService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;


    /*统计指定时间内的营业额*/
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //存入计算的日期
        List<LocalDate> dateList = getDataList(begin, end);

        //存入计算营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //计算出每一天精确的开始时间和结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //查询营业额
            Double turnover = orderMapper.getTurnover(beginTime, endTime, Orders.COMPLETED);
            turnoverList.add(turnover == null ? 0.0 : turnover);
        }

        return TurnoverReportVO.builder().dateList(StringUtils.join(dateList, ",")).turnoverList(StringUtils.join(turnoverList, ",")).build();
    }

    /*统计指定时间内的总用户和新用户的数据*/
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //计算时间
        List<LocalDate> dateList = getDataList(begin, end);

        List<Integer> totalUserList = new ArrayList<>();//总用户
        List<Integer> newUserList = new ArrayList<>();//新用户
        for (LocalDate localDate : dateList) {
            //开始时间
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            //结束时间
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            //计算新用户
            Integer newUser = userMapper.getyUserByDate(beginTime, endTime);
            //计算总用户
            Integer totalUser = userMapper.getyUserByDate(null, endTime);

            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }


        return UserReportVO.builder().dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ",")).build();
    }

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //获取时间
        List<LocalDate> dateList = getDataList(begin, end);

        //订单数列表
        List<Integer> totalOrderList = new ArrayList<>();
        //有效订单数
        List<Integer> validOrderList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //开始时间
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            //结束时间
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //每日订单数
            Integer totalOrder = orderMapper.getTurnoverInt(beginTime, endTime, null);
            //每日有效订单数
            Integer validOrder = orderMapper.getTurnoverInt(beginTime, endTime, Orders.COMPLETED);
            totalOrderList.add(totalOrder);
            validOrderList.add(validOrder);
        }

        //计算时间区间内的订单总数量
        Integer totalOrder = totalOrderList.stream().reduce(Integer::sum).get();
        /*
        reduce方法用于将流中的元素通过某种方式合并为单一的值。
        .get()：这是对reduce方法返回的Optional<Integer>对象调用get方法。Optional是Java 8中引入的一个容器类，它可能包含也可能不包含一个非null的值。get方法用于获取Optional对象中的值。如果Optional是空的，则调用get方法会抛出NoSuchElementException异常。

        */
        //计算时间区间内的有效订单数量
        Integer validOrder = validOrderList.stream().reduce(Integer::sum).get();

        //计算订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrder != 0) {
            orderCompletionRate = validOrder / totalOrder.doubleValue();
        }


        return OrderReportVO.builder().dateList(StringUtils.join(dateList, ",")).orderCountList(StringUtils.join(totalOrderList, ",")).validOrderCountList(StringUtils.join(validOrderList, ",")).totalOrderCount(totalOrder).validOrderCount(validOrder).orderCompletionRate(orderCompletionRate).build();
    }

    /*指定时间内销量前10*/
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        //开始时间
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        //结束时间
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> dishList = orderMapper.getSalesTop10(beginTime, endTime);
        String nameList = StringUtils.join(dishList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()), ",");
        String numberList = StringUtils.join(dishList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()), ",");


        return SalesTop10ReportVO.builder().nameList(nameList).numberList(numberList).build();
    }

    //计算日期
    private List<LocalDate> getDataList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.isAfter(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        return dateList;
    }

    /*导出运营报表*/
    @Override
    public void export(HttpServletResponse response) {
        //近30天的内容 不包含今天
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);

        //查询数据库获取到相应的营业数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));


        //通过POI把数据写到Excel文件中
        //以此文件为模板

        try (
                InputStream in = Files.newInputStream(Paths.get("D:\\Java\\sky-take-out\\sky-server\\src\\main\\resources\\template\\运营数据报表模板.xlsx"));
                XSSFWorkbook sheets = new XSSFWorkbook(in);
        ) {
            //获取标签页
            XSSFSheet sheet = sheets.getSheetAt(0);

            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            //获取单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            //填充近30天的营业数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //查询30天里每一天的营业数据
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                //获取行数
                row = sheet.getRow(7 + i);

                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            sheets.write(out);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        //通过HttpServletResponse将Excel文件下载到客户端

    }
}
